﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ThridGroup.ERP.DTO.JobGradeManagementDTO;
using ThridGroup.ERP.DTO.MaterielDto;

using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 物料services
    /// </summary>
    public class MaterielServices: ApplicationService, IMaterielServices
    {
        /// <summary>
        /// 物料仓储
        /// </summary>
        private readonly IRepository<MaterielModel,int> _materielServices;
        /// <summary>
        /// 物料分类仓储
        /// </summary>
        private readonly IRepository<MaterialType, int> _materielTypeServices;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="materielServices">物料仓储</param>
        /// <param name="_materielTypeServices">物料分类仓储</param>
        public MaterielServices(IRepository<MaterielModel, int> materielServices, IRepository<MaterialType, int> materielTypeServices)
        {
            _materielServices = materielServices;
            _materielTypeServices = materielTypeServices;
        }

        /// <summary>
        /// 获取物料分类级联树形结构
        /// </summary>
        /// <returns></returns>
        public async Task<List<MaterielTypeTreeSelectDto>> GetMaterialTypeTree()
        {
            var allTypes = await _materielTypeServices.GetListAsync();
            // 递归构建树
            List<MaterielTypeTreeSelectDto> BuildTree(int parentId)
            {
                return allTypes
                    .Where(x => x.ParentId == parentId)
                    .OrderBy(x => x.Index)
                    .Select(x => new MaterielTypeTreeSelectDto
                    {
                        Id = x.Id,
                        Label = x.MaterialTypeName,
                        Children = BuildTree(x.Id)
                    })
                    .ToList();
            }
            // 假设根节点ParentId为0
            return BuildTree(0);
        }

        /// <summary>
        /// 添加物料信息
        /// </summary>
        /// <returns></returns>
        public async Task<int> CreateMateriel(CreateMaterielDto createMaterielDto) 
        {
            var materiel = ObjectMapper.Map<CreateMaterielDto, MaterielModel>(createMaterielDto);
            var materie = await _materielServices.InsertAsync(materiel);
            return materie==null ? 0 : 1;
        }
        /// <summary>
        /// 显示物物料信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<CreateMaterielDto>> QueryMateriel(GetMaterielDto getMaterielDto) 
        {
        var materiellist=await _materielServices.GetListAsync();
        var materielTypelist=await _materielTypeServices.GetListAsync();
            
            // 两表联查：物料表与物料分类表联查
            var joinedData = (from materiel in materiellist
                             join materielType in materielTypelist
                             on materiel.MaterielTypeId equals materielType.Id
                             into materielTypeGroup
                             from materielType in materielTypeGroup.DefaultIfEmpty()
                             select new
                             {
                                 Materiel = materiel,
                                 MaterielType = materielType
                             }).ToList();
            // 应用查询条件
            var filteredData = joinedData.AsQueryable();
            
            //查询物料编号
            filteredData = filteredData.WhereIf(!string.IsNullOrEmpty(getMaterielDto.MaterielCode), 
                a => a.Materiel.MaterielCode.Contains(getMaterielDto.MaterielCode));
            
            //查询物料名称
            filteredData = filteredData.WhereIf(!string.IsNullOrEmpty(getMaterielDto.MaterielName), 
                a => a.Materiel.MaterielName.Contains(getMaterielDto.MaterielName));
            
            //按物料分类查询
            filteredData = filteredData.WhereIf(getMaterielDto.MaterielTypeId > 0, 
                a => a.Materiel.MaterielTypeId == getMaterielDto.MaterielTypeId);

            var result = filteredData.ToList().Select(a => {
                var dto = ObjectMapper.Map<MaterielModel, CreateMaterielDto>(a.Materiel);
                dto.MaterialTypeName = a.MaterielType != null ? a.MaterielType.MaterialTypeName : string.Empty;
                return dto;
            }).ToList();
            return result;
        }

        /// <summary>
        /// 修改物料信息
        /// </summary>
        /// <param name="dto">物料DTO</param>
        /// <returns>1成功，0失败</returns>
        public async Task<int> UpdateMateriel(CreateMaterielDto dto)
        {
            var materiel = ObjectMapper.Map<CreateMaterielDto, MaterielModel>(dto);
            var result = await _materielServices.UpdateAsync(materiel);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 批量删除物料信息
        /// </summary>
        /// <param name="ids">要删除的物料ID列表</param>
        public async Task BatchDeleteMateriel(List<int> ids)
        {
            if (ids == null || !ids.Any())
                return;
            await _materielServices.DeleteDirectAsync(a => ids.Contains(a.Id));
        }
    }
}
